package com.cskaoyan.order.service.impl;

import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.StringTokenizer;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public String createOrder(CreateOrderRequest request) {
        //创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    @Override
    public void cancelOrder(String orderId) {
        //TODO 取消订单的逻辑
        orderMapper.updateByOrderId(orderId);
        //TODO 返回商品锁定的数量
        //根据orderid 查询商品和商品的id
        Example example = new Example(OrderItem.class);
        example.createCriteria()
                .andEqualTo("orderId",orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(orderItems)) {
            for (OrderItem orderItem : orderItems) {
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();
                Stock stock = new Stock();
                stock.setItemId(itemId);
                stock.setLockCount(-num);
                stock.setStockCount(((long) num));
                stockMapper.updateStock(stock);
            }
        }

    }

    @Override
    public void deleteOrder(String orderId) {
        //TODO 返回锁定的数量  如果订单已经取消不用返回商品的数量
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order != null) {
            if (order.getStatus() == 0) {
                Example example = new Example(OrderItem.class);
                example.createCriteria()
                        .andEqualTo("orderId",orderId);
                List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
                if (!CollectionUtils.isEmpty(orderItems)) {
                    for (OrderItem orderItem : orderItems) {
                        Long itemId = orderItem.getItemId();
                        Integer num = orderItem.getNum();
                        Stock stock = new Stock();
                        stock.setItemId(itemId);
                        stock.setLockCount(-num);
                        stock.setStockCount(((long) num));
                        stockMapper.updateStock(stock);
                    }
                }
            }
        }

//        Example example2 = new Example(OrderItem.class);
//        example2.createCriteria()
//                .andEqualTo("orderId",orderId);
//        List<OrderItem> orderItems = orderItemMapper.selectByExample(example2);
//        if (!CollectionUtils.isEmpty(orderItems)) {
//            for (OrderItem orderItem : orderItems) {
//                Integer num = orderItem.getNum();
//                Long itemId = orderItem.getItemId();
//                //查到这个商品的库存
//                Stock stock1 = stockMapper.selectByPrimaryKey(itemId);
//                if (stock1 != null) {
//                    stock1.setStockCount(stock1.getStockCount() + num);
//                    stock1.setLockCount(stock1.getLockCount()-num);
//                    Example example3 = new Example(Stock.class);
//                    example3.createCriteria()
//                            .andEqualTo("itemId",itemId);
//                    stockMapper.updateByExampleSelective(stock1,example3);
//                }
//            }
//        }

        Example example = new Example(Order.class);
        example.createCriteria()
                .andEqualTo("orderId",orderId);
        orderMapper.deleteByPrimaryKey(orderId);
        //TODO 删除order_item
        Example example1 = new Example(OrderItem.class);
        example1.createCriteria()
                .andEqualTo("orderId",orderId);
        orderItemMapper.deleteByExample(example1);
        //TODO 删除order_shoping
        orderShippingMapper.deleteByPrimaryKey(orderId);


    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

}
